<?php

namespace app\controller\v1;

use app\model\CategoryModel;
use app\validate\CategoryValidate;
use think\App;

class Category extends System
{
    protected $validate;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->validate = new CategoryValidate();
    }


    /**
     * Notes: 添加
     * User: chenLei
     * Date: 9/28/25
     * @return \think\response\Json
     */
    public function add()
    {
        if (!$this->validate->scene('add')->check($this->params)) {
            return $this->errorJson($this->validate->getError());
        }

        $res = (new CategoryModel())->add($this->params);
        return $this->successJson();

    }


    /**
     * Notes: 编辑
     * User: chenLei
     * Date: 9/28/25
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function edit()
    {
        if (!$this->validate->scene('edit')->check($this->params)) {
            return $this->errorJson($this->validate->getError());
        }

        $categoryModel = new CategoryModel();
        $res = $categoryModel->edit($this->params);
        if ($res === false) {
            return $this->errorJson($categoryModel->getError());
        }
        return $this->successJson();
    }


    /**
     * Notes: 删除分类
     * User: chenLei
     * Date: 9/28/25
     * @return \think\response\Json
     */
    public function del()
    {
        if (!$this->validate->scene('del')->check($this->params)) {
            return $this->errorJson($this->validate->getError());
        }

        $categoryModel = new CategoryModel();
        $res = $categoryModel->del($this->params);
        if ($res === false) {
            return $this->errorJson($categoryModel->getError());
        }
        return $this->successJson();
    }

    /**
     * Notes: 列表
     * User: chenLei
     * Date: 9/28/25
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function list()
    {
        $categoryModel = new CategoryModel();
        $res = $categoryModel->list($this->params);

        return $this->successJson($res);
    }


    /**
     * Notes: 分类列表
     * User: chenLei
     * Date: 9/28/25
     * @return \think\response\Json
     */
    public function type()
    {
        return $this->successJson(CategoryModel::TYPE_ARRAY);
    }


    public function treeList()
    {
        if (!$this->validate->scene('treeList')->check($this->params)) {
            return $this->errorJson($this->validate->getError());
        }

        $categoryModel = new CategoryModel();
        $res = $categoryModel->treeList($this->params);
        if ($res === false) {
            return $this->errorJson($categoryModel->getError());
        }
        return $this->successJson($res);
    }
}